package org.example.mall.admin.controller.common;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.example.mall.admin.configuration.auth.check.CheckAuthHandlerChain;
import org.example.mall.admin.configuration.auth.code.ScenesConst;
import org.example.mall.admin.configuration.auth.code.SendCodeHandlerChain;
import org.example.mall.admin.configuration.resource.Inner;
import org.example.mall.admin.constant.auth.AuthTypeConst;
import org.example.mall.admin.configuration.exception.BaseException;
import org.example.mall.admin.util.R;
import org.example.mall.admin.util.SecurityUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hzq
 * @date 2021/12/23 13:10
 */
@Api(tags = "发送验证码")
@Inner(false)
@RestController
@RequestMapping("/common/code")
@AllArgsConstructor
public class SendCodeController {

    private final SendCodeHandlerChain sendCodeHandlerChain;
    private final CheckAuthHandlerChain checkAuthHandlerChain;

    @GetMapping("/send")
    @ApiOperation("发送验证码")
    public R<Object> send(@ApiParam(name = "scenes", value = "验证码场景") @RequestParam String scenes,
                          @ApiParam(name = "principal", value = "发送目标") @RequestParam(required = false, defaultValue = "") String principal,
                          @ApiParam(name = "handlerType", value = "发送类型") @RequestParam String handlerType) {
        if (StrUtil.isBlank(principal)) {
            // 登录图形验证码
            if (!(ScenesConst.LOGIN.equals(scenes) && AuthTypeConst.IMAGE.equals(handlerType))) {
                throw new BaseException("发送目标、不能为空");
            }
        }
        return sendCodeHandlerChain.sendCode(scenes, principal, handlerType);
    }

    @PostMapping("/check")
    @ApiOperation("检验验证码")
    public R<Object> check(@ApiParam(name = "scenes", value = "验证码场景") @RequestParam String scenes,
                           @ApiParam(name = "handlerType", value = "发送类型") @RequestParam String handlerType) {
        HttpServletRequest request = SecurityUtil.getHttpServletRequest();
        String principal = request.getParameter(AuthTypeConst.PRINCIPAL);
        String credentials = request.getParameter(AuthTypeConst.CREDENTIALS);
        return R.ofSuccess(checkAuthHandlerChain.check(scenes, principal, credentials, handlerType));
    }

}
